package com.wu.flandre.api;

import com.wu.flandre.annotation.ValidateAccessToken;
import com.wu.flandre.component.GlobalConstant;
import com.wu.flandre.component.WeChatAuthComponent;
import com.wu.flandre.entity.wechat.CreateXmlMsgEntity;
import com.wu.flandre.entity.wechat.WeChatAuthEntity;
import com.wu.flandre.entity.wechat.WeChatMsgTextEntity;
import com.wu.flandre.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Wechat dispacher
 *
 * @author wu
 */

@RestController
@Scope("prototype")
@Slf4j
public class Dispatcher {

    @Autowired
    WeChatAuthComponent weChatAuthComponent;

    @Autowired
    XmlUtil xmlUtil;

    /**
     * 微信认证
     *
     * @param entity
     * @return
     */
    @GetMapping("/doHandle")
    @ValidateAccessToken(value = false)
    public String weChatAuth(WeChatAuthEntity entity) {
        Boolean doAuth = weChatAuthComponent.doAuth(entity);
        if (doAuth) {
            log.info("WeChat Auth 认证成功");
            return entity.getEchostr();
        } else {
            log.error("WeChat Auth 认证失败");
            return null;
        }
    }

    /**
     * 微信消息转发
     *
     * @param request
     * @return
     */
    @PostMapping("/doHandle")
    @ValidateAccessToken(value = false)
    public String weChatHandle(HttpServletRequest request) {
        // Map<String, Object> xml = xmlUtil.commonXmlToMap(request);
        WeChatMsgTextEntity xml = xmlUtil.XmlToTextEntity(request);
        log.info(xml.toString());
        CreateXmlMsgEntity createXmlMsgEntity = new CreateXmlMsgEntity();
        createXmlMsgEntity.setToUserName(xml.getFromUserName());
        createXmlMsgEntity.setFromUserName(xml.getToUserName());
        createXmlMsgEntity.setMsgType(GlobalConstant.TEXT_MSG_TYPE);
        createXmlMsgEntity.setCreateTime(System.currentTimeMillis());
        createXmlMsgEntity.setContent(GlobalConstant.DEFAULT_MSG_RETURN);
        return xmlUtil.createXml(createXmlMsgEntity, GlobalConstant.TEXT_MSG_TYPE);
    }
}
